package com.app.qtjk.lsh.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.app.common.dataDictionary.DE.DE_DH_MONTH;
import com.app.common.dataDictionary.DE.DE_FILE_AVAILABLE;
import com.app.common.dataDictionary.DE.DE_OPPTIME;
import com.app.common.dataDictionary.DE.DE_USERID;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_CATEGORY;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_DETAIL;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_DUIHUANTIME;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_EXPIRYDATE;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_ID;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_IMGID;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_IMGNAME;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_IMGPATH;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_NEEDWEALTH;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_OPPTIME;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_SFUSED;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_TITLE;
import com.app.common.dataDictionary.DE.DE_USERWEALTH;
import com.app.common.dataDictionary.DE.DE_W_PRIZE_CATEGORY;
import com.app.common.dataDictionary.DE.DE_W_PRIZE_ID;
import com.app.common.dataDictionary.DE.DE_W_PRIZE_REMAINNUMBER;
import com.app.common.dataDictionary.PO.TFilePO;
import com.app.common.dataDictionary.PO.TMonthdhdataMaintainPO;
import com.app.common.dataDictionary.PO.TUserPO;
import com.app.common.dataDictionary.PO.TUserPrizePO;
import com.app.common.dataDictionary.PO.TWealthareaPrizePO;
import com.app.common.utils.DateFormatUtil;
import com.app.common.utils.FileUploadUtiles;
import com.app.common.utils.MD5Util;
import com.app.common.utils.ReqJsonUtil;
import com.app.common.utils.StringUtil;
import com.css.sword.kernel.base.annotation.Service;
import com.css.sword.kernel.base.annotation.ServiceContainer;
import com.css.sword.kernel.base.persistence.IPersistenceService;
import com.css.sword.kernel.base.persistence.SQLParam;
import com.css.sword.kernel.utils.SwordLogUtils;
import com.css.sword.kernel.utils.SwordPersistenceUtils;
import com.css.sword.kernel.utils.SwordSequenceUtils;
import com.css.sword.platform.web.event.IReqData;
import com.css.sword.platform.web.event.IResData;
import com.css.sword.platform.web.event.SwordReq;
import com.css.sword.platform.web.event.SwordRes;

@ServiceContainer
public class WealthareaService {

	private static SwordLogUtils log = SwordLogUtils
			.getLogger(WealthareaService.class);

	public WealthareaService() throws Exception {
		super();
	}

	/**
	 * 根据财富奖区id得到相应财富奖区的奖品列表
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Service(serviceName = "WealthareaService_getPrizeList")
	public IResData getPrizeList(IReqData req) throws Exception {

		log.debug("开始进入 WealthareaService_getPrizeList 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();

		IResData res = new SwordRes();
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		try {
			SQLParam sqlParam = new SQLParam();
			StringBuffer macroparam = new StringBuffer();
			// 获取前台post的数据
			String reqJson = ((SwordReq) req).getReqDataSet().getReqJson();
			Map<String, Object> postMap = ReqJsonUtil.json2map(reqJson);
			String wealthareaId = (String) ((ArrayList) postMap.get("wealthareaId")).get(0);
			String sortType = (String) ((ArrayList) postMap.get("sortType")).get(0);
			 
			if (sortType.equals("0")) {
				macroparam.append("'" + wealthareaId + "'");
			} else if (sortType.equals("1")) {
				macroparam.append("'" + wealthareaId
						+ "' ORDER BY w_prize_needwealth DESC");
			} else if (sortType.equals("2")) {
				macroparam.append("'" + wealthareaId
						+ "' ORDER BY w_prize_needwealth ASC");
			} else if (sortType.equals("3")) {
				macroparam.append("'" + wealthareaId
						+ "' ORDER BY w_prize_opptime DESC");
			} else if (sortType.equals("4")) {
				macroparam.append("'" + wealthareaId
						+ "' ORDER BY w_prize_opptime ASC");
			}
			sqlParam.addMacroParam(macroparam.toString());
			List<Map<String, Object>> wealrhareaPrizeMapList = dao.queryMapListByKey("WealthareaService_getPrizeList",sqlParam);
			for (int i = 0; i < wealrhareaPrizeMapList.size(); i++) {
				Map prizeDetailMap=wealrhareaPrizeMapList.get(i);
				Set<String> keySet = prizeDetailMap.keySet();
				for (String s : keySet) {
					if (s.equals("wPrizeStarttime")) {
						prizeDetailMap.put("wPrizeStarttime", DateFormatUtil.date2str((Date)prizeDetailMap.get(s),DateFormatUtil.DATE_FORMAT));
					}
					if (s.equals("wPrizeEndtime")) {
						prizeDetailMap.put("wPrizeEndtime", DateFormatUtil.date2str((Date)prizeDetailMap.get(s),DateFormatUtil.DATE_FORMAT));
					}
					if (s.equals("wPrizeDetailFj")) {
						String webfullpath = StringUtil.parse2String(FileUploadUtiles.getFileElemenstMap(StringUtil.parse2String(prizeDetailMap.get(s))).get("WebFullPath"));
						prizeDetailMap.put("wPrizeDetailFj", webfullpath);
					}
				}
			}
			hashMap.put("returnStatus", "true");
			hashMap.put("msg", "成功返回，未出现异常！");
			commonMap.put("wealrhareaPrizeMapList", wealrhareaPrizeMapList);
		} catch (Exception e) {
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "出现异常！");
		}finally{
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}
		return res;

	}

	/**
	 * 点击打开某个奖品详情
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Service(serviceName = "WealthareaService_getPrizeDetail")
	public IResData getPrizeDetail(IReqData req) throws Exception {

		log.debug("开始进入 WealthareaService_getPrizeDetail 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();

		IResData res = new SwordRes();
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		try {
			SQLParam sqlParam = new SQLParam();
			// 获取前台post的数据
			String reqJson = ((SwordReq) req).getReqDataSet().getReqJson();
			Map<String, Object> postMap = ReqJsonUtil.json2map(reqJson);
			
			String wPrizeId = (String)((ArrayList)postMap.get("wPrizeId")).get(0); 
			String userId = (String)((ArrayList) postMap.get("userId")).get(0);
			sqlParam.addParam(wPrizeId);

			Map<String, Object> prizeDetailMap = dao.queryMapByKey("WealthareaService_getPrizeDetail", sqlParam);
			
			sqlParam.clearParams();
			sqlParam.addParam(userId);
			sqlParam.addParam(wPrizeId);
			sqlParam.addParam("01");
			int curmonth = DateFormatUtil.getCurrentMonth();
			Object dbmonthObject = dao.queryColumnByKey("getUserMonthMaintainData", sqlParam, 1);
			System.out.println(dbmonthObject);
			int dbmonth = 0;
			if (null != dbmonthObject && !"".equals(dbmonthObject)) {
				dbmonth = (Integer) dbmonthObject;				
			} 
			if (dbmonth == curmonth) {
				prizeDetailMap.put("sfkDuiHuan", "0");
				prizeDetailMap.put("reason","该奖品为话费充值类奖品，每月只能兑换一次，您已兑换过，故不能兑换！");
			} else {
				sqlParam.clearParams();
				sqlParam.addParam(userId);
				int userWealth = (Integer) dao.queryColumnByKey("WealthareaService_getUserWealthByUserid", sqlParam, 1);
				int wPrizeNeedwealth = (Integer) prizeDetailMap.get("wPrizeNeedwealth");
				int wPrizeRemainnumber = (Integer) prizeDetailMap.get("wPrizeRemainnumber");
				Date wPrizeStarttimeReduce = DateFormatUtil.addDay(DateFormatUtil.str2date(StringUtil.parse2String(prizeDetailMap.get("wPrizeStarttime")), DateFormatUtil.DATE_FORMAT), -1);
				Date wPrizeEndtimeAfterAdd = DateFormatUtil.addDay(DateFormatUtil.str2date(StringUtil.parse2String(prizeDetailMap.get("wPrizeEndtime")), DateFormatUtil.DATE_FORMAT), 1);
				Date currentDate = DateFormatUtil.str2date(DateFormatUtil.getNowDate(), DateFormatUtil.DATE_FORMAT);
				if (currentDate.after(wPrizeStarttimeReduce) && currentDate.before(wPrizeEndtimeAfterAdd)) {
					if (userWealth >= wPrizeNeedwealth) {
						if (wPrizeRemainnumber > 0) {
							prizeDetailMap.put("sfkDuiHuan", "1");
						} else {
							prizeDetailMap.put("sfkDuiHuan", "0");
							prizeDetailMap.put("reason","该奖品已兑换完毕，没有剩余量，故不能兑换！");
						}
					} else {
						prizeDetailMap.put("sfkDuiHuan", "0");
						prizeDetailMap.put("reason", "您的财富值不够兑换该奖品，故不能兑换！");
					}
				} else {
					prizeDetailMap.put("sfkDuiHuan", "0");
					prizeDetailMap.put("reason", "该奖品已过起止时间，故不能兑换！");
				}
			}
			Set<String> keySet = prizeDetailMap.keySet();
			for (String s : keySet) {
				if (s.equals("wPrizeStarttime")) {
					prizeDetailMap.put("wPrizeStarttime", DateFormatUtil.date2str((Date)prizeDetailMap.get(s),DateFormatUtil.DATE_FORMAT));
				}
				if (s.equals("wPrizeEndtime")) {
					prizeDetailMap.put("wPrizeEndtime", DateFormatUtil.date2str((Date)prizeDetailMap.get(s),DateFormatUtil.DATE_FORMAT));
				}
				if (s.equals("wPrizeDetailFj")) {
					String webfullpath = StringUtil.parse2String(FileUploadUtiles.getFileElemenstMap(StringUtil.parse2String(prizeDetailMap.get(s))).get("WebFullPath"));
					prizeDetailMap.put("wPrizeDetailFj", webfullpath);
				}
			}
			hashMap.put("returnStatus", "true");
			hashMap.put("msg", "成功返回，未出现异常！");
			commonMap.put("prizeDetailMap", prizeDetailMap);
		} catch (Exception e) {
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "出现异常！");
		}finally{
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}
		return res;

	}

	/**
	 * 使用财富值兑换奖品
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
	@Service(serviceName = "WealthareaService_exchangePrize")
	public IResData exchangePrize(IReqData req) throws Exception {

		log.debug("开始进入 WealthareaService_exchangePrize 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		dao.getTransactionService().setAutoCommit(false);
		IResData res = new SwordRes();
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		String DuiHuanSuccess = "false";
		try {
			SQLParam param = new SQLParam();
			// 获取前台post的数据
			String wPrizeId = ReqJsonUtil.getPostParam(req,"wPrizeId");
			String userId = ReqJsonUtil.getPostParam(req,"userId");
			String lshToken = ReqJsonUtil.getPostParam(req,"lshToken");
			String lshTokenstr=MD5Util.MD5(wPrizeId+MD5Util.diyStr);
			if (!lshTokenstr.equals(lshToken)) {
				hashMap.put("returnStatus", "false");
				hashMap.put("msg", "口令错误！");
				commonMap.put("commonData", hashMap);
				commonList.add(commonMap);
				res.addListWithDataName("returnData", commonList);
				return res;
			}
			param.addParam(userId);
			// 获取某用户的财富值
			TUserPO userPO = dao.queryPOByKey("UserService_getUserPOByID",param,TUserPO.class);
			int userwealth = userPO.getUserwealth().value;
			param.clearParams();
			param.addParam(wPrizeId);
			TWealthareaPrizePO prizePO = dao.queryPOByKey("WealthareaService_getPrizeDetailAllData", param, TWealthareaPrizePO.class);
			String wPrizeCategory = prizePO.getWPrizeCategory().value;

			if (prizePO!=null) {
				// 获取兑换奖品所需要的财富值和该奖品的剩余量
				int wPrizeNeedwealth = prizePO.getWPrizeNeedwealth().value;
				int wPrizeRemainnumber = prizePO.getWPrizeRemainnumber().value;
				try {
					//用户兑换奖品扣除财富值
					userPO.setUserwealth(new DE_USERWEALTH(userwealth - wPrizeNeedwealth));
					int i = dao.updatePO(userPO);
					int wpr=wPrizeRemainnumber - 1;
					if (wpr<0) {
						wpr=0;
					}
					prizePO.setWPrizeRemainnumber(new DE_W_PRIZE_REMAINNUMBER(wpr));
					int j = dao.updatePO(prizePO);
					TUserPrizePO tUserPrizePO = new TUserPrizePO();
					tUserPrizePO.setUserprizeId(new DE_USERPRIZE_ID(SwordSequenceUtils.generateRandomString()));
					tUserPrizePO.setWPrizeId(new DE_W_PRIZE_ID(wPrizeId));
					tUserPrizePO.setUserid(new DE_USERID(userId));
					tUserPrizePO.setUserprizeTitle(new DE_USERPRIZE_TITLE(prizePO.getWPrizeTitle().value));
					tUserPrizePO.setUserprizeNeedwealth(new DE_USERPRIZE_NEEDWEALTH(wPrizeNeedwealth));
					//话费充值类奖品一个月只可以兑换一次
					if (null != wPrizeCategory) {
						if ("01".equals(wPrizeCategory)) {
							String wPrizeFileid = prizePO.getWPrizeFileid().value;
							param.clearParams();
							param.addParam("tWealthareaPrize");
							param.addParam(wPrizeFileid);
							TFilePO tFilePO = dao.queryPOByKey("getImgFileBy2RelatedID", param, TFilePO.class);
							tUserPrizePO.setUserprizeImgpath(new DE_USERPRIZE_IMGPATH(tFilePO.getFileImgpath().value));
							tUserPrizePO.setUserprizeImgid(new DE_USERPRIZE_IMGID(tFilePO.getFileImgid().value));
							tUserPrizePO.setUserprizeImgname(new DE_USERPRIZE_IMGNAME(tFilePO.getFileImgname().value));
							tUserPrizePO.setUserprizeCategory(new DE_USERPRIZE_CATEGORY(wPrizeCategory));
							tFilePO.setFileAvailable(new DE_FILE_AVAILABLE("0"));
							int k = dao.updatePO(tFilePO);
							int curmonth = DateFormatUtil.getCurrentMonth();
							TMonthdhdataMaintainPO po = new TMonthdhdataMaintainPO();
							po.setUserid(new DE_USERID(userId));
							po.setWPrizeId(new DE_W_PRIZE_ID(wPrizeId));
							po.setWPrizeCategory(new DE_W_PRIZE_CATEGORY("01"));
							po.setDhMonth(new DE_DH_MONTH(curmonth));
							po.setOpptime(new DE_OPPTIME(new Date()));
							int m = dao.insertPO(po);
						} else if ("99".equals(wPrizeCategory) || "02".equals(wPrizeCategory)){
							tUserPrizePO.setUserprizeImgpath(new DE_USERPRIZE_IMGPATH(prizePO.getWPrizeImgpath().value));
							tUserPrizePO.setUserprizeImgid(new DE_USERPRIZE_IMGID(prizePO.getWPrizeImgid().value));
							tUserPrizePO.setUserprizeImgname(new DE_USERPRIZE_IMGNAME(prizePO.getWPrizeImgid().value));
							tUserPrizePO.setUserprizeCategory(new DE_USERPRIZE_CATEGORY(wPrizeCategory));
						}
						tUserPrizePO.setUserprizeExpirydate(new DE_USERPRIZE_EXPIRYDATE(prizePO.getWPrizeExpirydate().value));
						tUserPrizePO.setUserprizeDetail(new DE_USERPRIZE_DETAIL(prizePO.getWPrizeDetail().value));
						tUserPrizePO.setUserprizeSfused(new DE_USERPRIZE_SFUSED("0"));
						tUserPrizePO.setUserprizeDuihuantime(new DE_USERPRIZE_DUIHUANTIME(new Date()));
						tUserPrizePO.setUserprizeOpptime(new DE_USERPRIZE_OPPTIME(new Date()));
						int n = dao.insertPO(tUserPrizePO);
						if (i>0 && j>0 && n>0) {
							dao.commitAll();
							DuiHuanSuccess = "true";
						}
						hashMap.put("DuiHuanSuccess", DuiHuanSuccess);
						hashMap.put("DuiHuanUseWealth", wPrizeNeedwealth);
						hashMap.put("returnStatus", "true");
						hashMap.put("msg", "成功返回，未出现异常！");
					}else {
						hashMap.put("DuiHuanSuccess", DuiHuanSuccess);
						hashMap.put("returnStatus", "false");
					}
				} catch (Exception e) {
					dao.rollbackAll();
					log.debug("---------------兑换奖品异常！数据已回滚！---------------");
					e.printStackTrace();
					hashMap.put("DuiHuanSuccess", DuiHuanSuccess);
					hashMap.put("returnStatus", "false");
					hashMap.put("msg", "兑换奖品出现异常！");
				}
			}
		} catch (Exception e) {
			dao.rollbackAll();
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "出现异常！");
		} finally{
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}
		return res;

	}

}